import React from 'react';

import Header from '../common/Header';
import CKModal from '../components/CKModal';
import Validate from '../common/Validate';
import moment from 'moment';
import {
    Button,
    Input,
    Form,
    Grid,
    Col,
    Selected
} from 'amazeui-react';

import Fetch from '../common/Fetch';

import $ from 'jquery';

class FuncEdit extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            data:{
                fun_id:null,
                fun_name:'',
                tmp_id:'',
                fun_class:'',
                fun_function:'',
                fun_var:'',
                fun_params:'',
                created_date:null,
                modified_date:null
            },
            class_data:[],
            funcs_data:[],
            params_data:[],
            param_type:[
                {label:'字符串',value:'string'},
                {label:'数字',value:'number'}
            ],
            is_save:false,
            type:this.props.params.id ? 'edit':'add',
            init:false,
            title:this.props.params.id?'修改调用函数':'添加调用函数'
        };

        this.class_name = '';
    }

    componentDidMount() {
        this.showTitle();
        this.loadClassList();
    }

    loadFuncInfo() {
        Fetch('/cms/func_manage/info',{cipher_id:this.props.params.id},(res)=>{
            if (res.status) {
                let data = this.state.data;
                $.map(data,(item,index)=>{
                    data[index] = res.data[index];
                });
                this.setState({
                    data:data,
                    params_data:JSON.parse(data.fun_params)
                });
                this.loadFuncList(data.fun_class);
            } else {
                this.modal.alert('错误','获取方法信息出错！');
            }
        },(e)=>{
            this.modal.alert('错误','调用失败！'+e);
        });
    }

    showTitle() {
        this.setState({
            title:this.state.title+' - '+this.props.location.query.name
        })
    }

    loadClassList() {
        Fetch('/cms/func_manage/get_publish_class_list',{},(res)=>{
            if (res.status) {
                this.setState({
                    class_data:res.data
                });
            }
            if (this.state.type === 'edit') {
                this.loadFuncInfo();
            }
        });
    }

    loadFuncList = (class_name) => {
        Fetch('/cms/func_manage/get_publish_funcs',{class_name:class_name},(res)=>{
            if (res.status) {
                let data = this.state.data;
                data.fun_class = class_name;
                this.setState({
                    funcs_data:res.data,
                    data:data
                });
                this.class_name = class_name;
            }
        });
    };

    loadParams = (func_name) => {
        Fetch('/cms/func_manage/get_func_params',{class_name:this.class_name,func_name:func_name},(res)=>{
            if (res.status) {
                let data = this.state.data;
                data.fun_function = func_name;
                this.setState({
                    params_data:res.data,
                    data:data
                });
            }
        });
    };

    changeHandler(field){
        return (e)=>{
            let info = this.state.data;
            info[field] = e.target.value;
            this.setState({data:info});
        }
    }

    paramChangeHandler(index) {
        return (e)=>{
            let params = this.state.params_data;
            params[index].val = e.target.value;
            this.setState({
                params_data:params
            })
        };
    }

    paramSelectHandler(index) {
        return (value)=>{
            let params = this.state.params_data;
            params[index].type = value;
            this.setState({
                params_data:params
            })
        };
    }

    checkData() {
        let valid = {
            'fun_name':{role:'s2-20',errmsg:'函数名称为2到20个字符'},
            'fun_var':{role:'*',errmsg:'变量名不能为空'},
            'fun_class':{role:'*',errmsg:'请选择一个函数类'},
            'fun_function':{role:'*',errmsg:'请选择一个函数方法'}
        };

        let data = this.state.data;
        data.fun_params = JSON.stringify(this.state.params_data);
        try {
            Validate.inst().checkData(data,valid);
            return data;
        } catch (e) {
            this.modal.alert('错误',e);
            return false;
        }
    }

    save = ()=>{
        let data = this.checkData();
        if (data === false) return;

        if (this.state.is_save) return;
        this.setState({
            is_save:true
        });

        Fetch('/cms/func_manage/save',{data:data,tmp_id:this.props.location.query.tmp_id},(res)=>{
            if (res.status) {
                this.modal.alert('成功','保存菜单数据成功!',()=>{
                    this.context.router.goBack();
                });
            } else {
                this.modal.alert('失败','保存菜单失败!!');
                this.setState({
                    is_save:false
                });
            }
        },()=>{
            this.modal.alert('失败','远程调用失败!!');
            this.setState({
                is_save:false
            });
        });
    };

    render() {
        let data = this.state.data;
        return (
            <div className="content">
                <Header title={this.state.title} back={true}/>
                <div className="content_main">
                    <div style={{marginBottom:'20px'}}>
                        <h4 className="title">调用函数信息</h4>
                    </div>
                    <Form ref="from" horizontal style={{marginTop:'20px'}}>
                        <Input id="menu_name" ref="menu_name" label="函数名称"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.fun_name}
                               placeholder="函数名称为2到40个字符"
                               onChange={this.changeHandler('fun_name')}
                        />
                        <Input id="menu_icon" ref="menu_icon" label="回调变量名"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               placeholder="模板内使用的变量名称"
                               value={data.fun_var}
                               onChange={this.changeHandler('fun_var')}
                        />
                        <div className="am-form-group">
                            <label className="am-u-sm-2 am-form-label">
                                函数类
                            </label>
                            <div className="am-u-sm-4 am-u-end">
                                <Selected onChange={this.loadFuncList}
                                          placeholder="请选择函数类"
                                          btnStyle="success" data={this.state.class_data}
                                          value={data.fun_class || ''}/>
                                <Selected onChange={this.loadParams}
                                          placeholder="请选择函数"
                                          btnStyle="warning" data={this.state.funcs_data}
                                          value={data.fun_function || ''}/>
                            </div>
                        </div>
                        <div className="am-form-group">
                            <label className="am-u-sm-2 am-form-label">

                            </label>
                            <div className="am-u-sm-4 am-u-end">
                                {this.state.params_data.map((item,index)=>{
                                    return (
                                        <Grid collapse>
                                            <Col sm={2}>
                                                <label className="am-form-label">{item.name}</label>
                                            </Col>
                                            <Col sm={3}>
                                                <Selected onChange={this.paramSelectHandler(index)}
                                                          placeholder="参数类型"
                                                          btnStyle="default" data={this.state.param_type}
                                                          value={item.type}/>
                                            </Col>
                                            <Col sm={4} end>
                                                <Input placeholder="参数值" onChange={this.paramChangeHandler(index)} defaultValue={item.val}/>
                                            </Col>
                                        </Grid>
                                    );
                                })}
                            </div>
                        </div>
                        <Input label="添加时间" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={moment.unix(data.created_date).format('YYYY-MM-DD HH:mm:ss')}
                               disabled
                        />
                        <Input label="修改时间" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={moment.unix(data.modified_date).format('YYYY-MM-DD HH:mm:ss')}
                               disabled
                        />
                    </Form>
                    <div className="am-form-group">
                        <div className="am-u-sm-2">
                            &nbsp;
                        </div>
                        <div className="am-u-sm-4 am-u-end">
                            <Button amStyle="primary"
                                    onClick={this.save}
                                    disabled={this.state.is_save}
                            >
                                {this.state.is_save?'保存中...':'保存'}
                            </Button>
                        </div>
                    </div>
                </div>
                <CKModal ref={(c)=>{this.modal = c}}/>
            </div>
        );
    }
}

FuncEdit.contextTypes = {
    router: React.PropTypes.object
};

export default FuncEdit;